package com.nsi.controller.portal;

import com.google.common.collect.Maps;
import com.nsi.async.AsyncTask;
import com.nsi.util.RedisUtils;
import com.nsi.common.ServerResponse;
import com.nsi.config.DynamicDataSourceHolder;
import com.nsi.pojo.Exhibitor;
import com.nsi.service.*;
import com.nsi.util.HttpRequest;
import com.nsi.util.PropertiesUtil;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author Li Yan
 * @create 2018-09-14
 **/

@RequestMapping("/CommonApi")
@Controller
@Api(value = "/CommonApi", description = "通用功能接口")
@Slf4j
public class CommonApiController {

    public static final String FLAG = "master_flag";

    public static final String EXHIBITION_FLAG = "exhibition_flag";

    public static final String MASTER_KEY = "master_";

    public static final String Exhibition_KEY = "exhibition_";

    @Autowired
    private IWxPayService iWxPayService;
    @Autowired
    private ICommonApiService iCommonApiService;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private AsyncTask asyncTask;
    @Autowired
    private ExhibitorService exhibitorService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private IFileService iFileService;
    @Autowired
    private CommonMiniProgremService commonMiniProgremService;
    @Autowired
    private IArticleService iArticleService;

    /**
     * 微信分享
     *
     * @param URL
     * @return
     */
    @RequestMapping(value = "/WxShare.do")
    @ResponseBody
    @ApiOperation(value = "微信分享", httpMethod = "POST")
    public ServerResponse<String> WxShare(String URL) {
        DynamicDataSourceHolder.setDataSource("dataSource1");
        return iWxPayService.wxChatShare(URL);
    }

    /**
     * @param url
     * @return
     */
    @RequestMapping(value = "/ErrorNotify.do")
    @ResponseBody
    @ApiOperation(value = "接口异常警告", httpMethod = "POST")
    public ServerResponse<String> ErrorNotify(String env, String data, String url, String api, String errMsg) {

        return iCommonApiService.ErrorNotify(env, data, url, api, errMsg);
    }

    //微信小程序登录（研究院商城）

    /**
     * @param code
     * @return
     */
    @RequestMapping(value = "/MiniProgramLogin_shop.do")
    @ResponseBody
    @ApiOperation(value = "微信小程序登录（研究院商城）", httpMethod = "POST")
    public ServerResponse<String> MiniProgramLogin_shop(String code) {
        return iCommonApiService.MiniProgramLogin_shop(code);
    }

    //接口加密-获取服务器时间戳

    /**
     * @return
     */
    @RequestMapping(value = "/getServerTime.do")
    @ResponseBody
    @ApiOperation(value = "获取服务器时间戳", httpMethod = "POST")
    public ServerResponse<String> getServerTime() {
        return ServerResponse.createBySuccess(String.valueOf(System.currentTimeMillis()));
    }

    //接口加密-验证加密code

    /**
     * @return
     */
    @RequestMapping(value = "/checkVerityCode.do")
    @ResponseBody
    @ApiOperation(value = "接口加密-验证加密code", httpMethod = "POST")
    public ServerResponse<String> checkVerityCode(String code) {
        String[] myArray = iCommonApiService.checkVerityCode(code);

        if (myArray[0].equals("0")) {
            return ServerResponse.createBySuccess(myArray[0], myArray[1]);
        } else {
            return ServerResponse.createByErrorCodeMessage(Integer.valueOf(myArray[0]), myArray[1]);
        }
    }


    //用户IP地址查询定位

    /**
     * @return
     */
    @RequestMapping(value = "/ipToLocation.do")
    @ResponseBody
    @ApiOperation(value = "用户IP地址查询定位", httpMethod = "POST")
    public ServerResponse<String> ipToLocation(HttpServletRequest request) {
//        获取真实ip地址
//         String ip = request.getHeader("x-forwarded-for");
//         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//             ip = request.getHeader("Proxy-Client-IP");
//         }
//         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//             ip = request.getHeader("WL-Proxy-Client-IP");
//         }
//         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//             ip = request.getRemoteAddr();
//         }
//         System.out.println("ip" + ip);
// //        淘宝ip地址查询接口
//         String requestUrl = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip;
//         String resJson = null;
//         try {
//             resJson = HttpRequest.sendPost(requestUrl, null);
//         } catch (Exception e) {
//             e.printStackTrace();
//             return ServerResponse.createByErrorMessage("无结果");
//         }
//         System.out.println("resJson " + resJson);
//
//         JSONObject jsonObject = JSONObject.parseObject(resJson);
//         String sityName = jsonObject.getJSONObject("data").getString("city");
//         System.out.println(sityName);

        return ServerResponse.createBySuccess("返回成功", "北京");
    }


    /**
     * 发送验证码功能
     *
     * @return
     */
    @RequestMapping(value = "/sendSms.do", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "发送验证码", httpMethod = "POST")
    public ServerResponse sendSms(@RequestParam("mobile") String mobile) {
        if (StringUtils.isEmpty(mobile)) {
            return ServerResponse.createByErrorMessage("手机号不能为空");
        }
        iUserService.sendSms(mobile);
        return ServerResponse.createBySuccess("发送成功");
    }

    /**
     * 发送成功短信
     *
     * @param telphone
     * @return
     */
    @RequestMapping(value = "/send_pay_message.do")
    @ResponseBody
    @ApiOperation(value = "发送成功短信", httpMethod = "GET")
    public ServerResponse sendSucMessage(@RequestParam("telphone") String telphone,
                                         @RequestParam("activeName") String activeName) {
        asyncTask.sendPayMessage(telphone, activeName);
        return ServerResponse.createBySuccess();
    }


    @RequestMapping(value = "/thumb_up_close.do", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "通用点赞功能-已关闭", httpMethod = "POST")
    public ServerResponse thumbUp(Integer exhibitorId) {
        return ServerResponse.createByErrorMessage("活动已结束");
    }


    @RequestMapping(value = "/thumb_up_master02.do", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "通用点赞功能-备用", httpMethod = "POST")
    public ServerResponse master_thumb_up02(Integer exhibitorId) {
        exhibitorService.thumbup(exhibitorId);
        return ServerResponse.createBySuccess();
    }


    @RequestMapping(value = "/thumb_up_master.do", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "校长点赞", httpMethod = "POST")
    public ServerResponse thumbupMaster(@RequestParam("masterId") Integer exhibitorId) {
        return ServerResponse.createByErrorMessage("投票通道已关闭");
    }


    @RequestMapping(value = "/thumb_up_exhibition.do", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "机构服务商点赞", httpMethod = "POST")
    public ServerResponse thumb_up_exhibition(@RequestParam("exhibitorId") Integer exhibitorId) {
        String flag = RedisUtils.searchRedis(EXHIBITION_FLAG);
        if (null == flag || !"0".equals(flag)) {
            return ServerResponse.createByErrorMessage("投票通道已结束");
        }
        String ipAddress = this.getIpAddress(request).replaceAll(":", ".");
        log.info("【点赞功能统计】ip:{}", ipAddress);
        int num = RedisUtils.incrment(ipAddress, 60);
        if (num >= 100) {
            return ServerResponse.createByError("当前投票数人过多,请稍后访问");
        }
        int count = RedisUtils.incrment(Exhibition_KEY + exhibitorId);
        int randomNum = this.random();
        if (count >= randomNum) {
            // 查询改值
            Exhibitor exhibitor = exhibitorService.selectById(exhibitorId);
            exhibitor.setThumbValue(exhibitor.getThumbValue() + count);
            exhibitorService.updateById(exhibitor);
            // 清空Redis
            RedisUtils.alterRedis(Exhibition_KEY + exhibitorId, "0");
        }
        return ServerResponse.createBySuccess();
    }

    @RequestMapping(value = "/thumb_up_exhibition_token.do", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "机构服务商点赞_token验证", httpMethod = "POST")
    public ServerResponse thumb_up_exhibition_token(@RequestParam("exhibitorId") Integer exhibitorId,
                                                    @RequestParam(value = "token", defaultValue = "0") String token) {
        String flag = RedisUtils.searchRedis(EXHIBITION_FLAG);
        if (null == flag || "1".equals(flag)) {
            return ServerResponse.createByErrorMessage("投票通道已结束");
        }
        if (!token.equals(flag)) {
            return ServerResponse.createByErrorMessage("验证失败");
        }
        String ipAddress = this.getIpAddress(request).replaceAll(":", ".");
        log.info("【点赞功能统计】ip:{}", ipAddress);
        int num = RedisUtils.incrment(ipAddress, 60);
        if (num >= 100) {
            return ServerResponse.createByError("当前投票数人过多,请稍后访问");
        }
        int count = RedisUtils.incrment(Exhibition_KEY + exhibitorId);
        int randomNum = this.random();
        if (count >= randomNum) {
            // 查询改值
            Exhibitor exhibitor = exhibitorService.selectById(exhibitorId);
            exhibitor.setThumbValue(exhibitor.getThumbValue() + count);
            exhibitorService.updateById(exhibitor);
            // 清空Redis
            RedisUtils.alterRedis(Exhibition_KEY + exhibitorId, "0");
        }
        return ServerResponse.createBySuccess();
    }


//    --------------------工具类-------------------------


    /**
     * 图片上传-对象存储-普通文件类型
     *
     * @param file
     * @return
     */
    @RequestMapping(value = "/upload.do", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "图片上传-对象存储-普通文件类型", httpMethod = "POST")
    public ServerResponse upload(@RequestParam(value = "file", required = false) MultipartFile file, String type) {
        if (StringUtils.isBlank(type)) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        String targetFileName = iFileService.upload(file, type);
        if ("".equalsIgnoreCase(targetFileName)) {
            return ServerResponse.createByErrorMessage("文件格式错误");
        }
        String url = PropertiesUtil.getProperty("aliyun.image.url") + type + targetFileName;
        Map resultMap = Maps.newHashMap();
        resultMap.put("uri", targetFileName);
        resultMap.put("url", url);
        return ServerResponse.createBySuccess(resultMap);
    }

    /**
     * 图片上传-对象存储-Base64类型
     *
     * @param strImage
     * @param type
     * @return
     */
    @RequestMapping(value = "/upImage_base64.do", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "图片上传-对象存储-Base64类型", httpMethod = "POST")
    public ServerResponse upImage_base64(@RequestParam("strImage") String strImage,
                                         @RequestParam("type") String type) {
        Map map = Maps.newHashMap();
        if (StringUtils.isBlank(strImage) || StringUtils.isBlank(type)) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        String targetFileName = iFileService.base64Upload(strImage, type);
        String url = PropertiesUtil.getProperty("aliyun.image.url") + type + targetFileName;
        map.put("uri", targetFileName);
        map.put("url", url);
        return ServerResponse.createBySuccess(map);
    }

    /**
     * 生成小程序码
     *
     * @param scene
     * @param page
     * @return
     */
    @RequestMapping(value = "/getMiniProgremQR_Unlimited.do", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "图片上传-对象存储-Base64类型", httpMethod = "POST")
    public ServerResponse getMiniProgremQR_Unlimited(@RequestParam("scene") String scene,
                                                     @RequestParam("page") String page) {

        String result = commonMiniProgremService.getMiniProgremQR_Unlimited(page, scene);
        return ServerResponse.createBySuccess("success", result);
    }

    /**
     * 验证短信验证码
     *
     * @param mobile
     * @param code
     * @return
     */
    @RequestMapping(value = "/check_code.do", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "验证短信验证码", httpMethod = "POST")
    public ServerResponse checkCode(@RequestParam("mobile") String mobile,
                                    @RequestParam("code") String code) {
        // 获取缓存验证码
        String numCode = RedisUtils.searchRedis("SMS_" + mobile);
        if (StringUtils.isEmpty(numCode)) {
            return ServerResponse.createByErrorMessage("手机号或验证码不正确");
        }
        if (!numCode.equals(code)) {
            return ServerResponse.createByErrorMessage("手机验证码不正确");
        }
        return ServerResponse.createBySuccess("验证成功");
    }


    /**
     * 百度链接收录-主动
     *
     * @return
     */
    @RequestMapping(value = "/baiduLinkSubmit.do", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "百度链接收录", httpMethod = "POST")
    public ServerResponse baiduLinkSubmit(@RequestParam(value = "siteUrl", required = false) String siteUrl) {

        String url = "http://data.zz.baidu.com/urls?site=https://www.xinxueshuo.cn&token=0Uxf8ITc9JSwMNjf";
        String pram = "";
        if (StringUtils.isEmpty(siteUrl)) {
            // pram="https://www.xinxueshuo.cn/article/20905.html,https://www.xinxueshuo.cn/article/20899.html";
            String urlString = iArticleService.baiduUrlList("", "", 1, 500);
            System.out.println("urlString:" + urlString);
            pram = urlString;
        } else {
            pram = siteUrl;
        }

        String backStr = HttpRequest.sendPost(url, pram);
        System.out.println("backStr:" + backStr);

        return ServerResponse.createBySuccess("操作成功");
    }


//    --------------------工具类-------------------------


    /**
     * 40——50 随机数
     */
    private int random() {
        return (int) (10 * Math.random() + 40);
    }

    /**
     * 获取真实IP
     *
     * @param request
     */
    public String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

}
